package com.ming.Controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ming.Bean.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:weiming
 * @Date:2020/11/15
 */
@Controller

public class UserController {

    @Autowired
    ObjectMapper objectMapper;

    @GetMapping("stu")
    @ResponseBody
    public Map hello(){
        Student student = new Student();
        student.setStuid(1);
        student.setStuname("test");
        student.setTeaId(2);
        student.setBirthDate(new Date());
        Map map = new HashMap();
        map.put("data",student);
        return  map;
    }

    @RequestMapping("serialization")
    public String serializa(){
        Student student = new Student();
        student.setStuid(1);
        student.setStuname("test");
        student.setTeaId(2);
        student.setBirthDate(new Date());
        try {
            String stu = objectMapper.writeValueAsString(student);
            return stu;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return  null;
    }

    @RequestMapping("readJson")
    public void readJson(){
        String json = "{\"name\":\"weiming\",\"age\":26}";
        try {
           JsonNode node =  objectMapper.readTree(json);
           String name = node.get("name").asText();
           int age = node.get("age").asInt();
            System.out.println("姓名="+name+" 年龄="+age);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("bindObject")
    public void  bindObject(){
        String json = "{\"name\":\"weiming\",\"age\":26}";
        try {
            Student student =  objectMapper.readValue(json, Student.class);
            System.out.println(student.getStuname());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("date")
    public String form(){
        return "date";
    }
}
